<?php
/**
 +------------------------------------------------------------------------------
 * OrderSelect订单查询统计类
 +------------------------------------------------------------------------------
 * @category   SubAction
 * @package  app
 * @subpackage  Action
 * @author   朝闻道 <admin@iic.cn>
 * @date 2013-5-15
 * @time  下午5:53:53
 +------------------------------------------------------------------------------
 *
 */
class OrderSelect {
	protected $line = '';
	protected $orderdao;
	protected $platform;
	protected $debug;
	function __construct($platform = 'SMW01') {
		$this->orderdao = M ( 'Order' );
		$this->platform = strtoupper ( $platform );
	}
	/**
	 * 获取订单列表（SYS）
	 *
	 * @param array $where
	 *        	查询的条件
	 * @param string $limit
	 *        	查询条数 all的时候只返回总条数
	 * @param string $orderby        	
	 * @return array $data
	 *         @date 2013-5-15
	 *         @time 下午5:55:20
	 */
	function order_list($where = array(), $limit = '0,25', $orderby = 'id DESC') {
		// 获取订单列表（SYS）
		$this->line = 'order_list::' . __LINE__;
		$limit = strtolower ( $limit );
		if ($limit == 'all') {
			$count = $this->orderdao->where ( $where )->count ();
// 			echo $this->orderdao->getLastSql();
			return $count;
		}
		$data = $this->orderdao->where ( $where )->order ( $orderby )->limit ( $limit )->select ();
// 		echo $this->orderdao->getLastSql();
		if ($where ['platform'] == 'O2O') {
			// 暂时不做区分
		}
		return $data;
	} // end order_list
	
	/**
	 * 二维数组返回一维或字符串
	 * @param array $_arr
	 * @param string $_field
	 * @param string $_type 1为数组 2为字符串
	 * @return multitype:array|multitype:string
	 */
	function _arr2to1($_arr,$_field = 'id',$_type = '1'){
		if ( ! $_arr ) return array();
		$arrayids = array();
		foreach ($_arr as $k => $v){
			$arrayids[$k] = $v[$_field];
		}
		if($_type != '1') $arrayids = implode(',',$arrayids);
	
		return $arrayids;
	}
	
	/**
	 * 返回用户的订单ID
	 * @param int $_uid
	 * @return array $order
	 */ 
	function b2b_order_ids($_uid){
		$model = M('Order');
		$where = array();
		$where['userid'] = $_uid;
		$where['platfrom'] = 'SMW01';
		$order = $model->field('id')->where($where)->order('id DESC')->select();
		$order = $this->_arr2to1($order,'id');
		return $order;
	}
	
	/**
	 * 送PV
	 * @param int $_uid
	 * @param int $_mun
	 * @param int $_sn
	 * @return boolean $reid
	 */
	function b2b_pv($_uid,$_mun,$_sn){
		$_uid && $_mun ? true : exit('参数不能为空！在 OrderSelect 中，第'.__LINE__.'行');
		$pvm = M('UserMoney');
		$pva = M('UserAssets');
		$where = array();
		$where['userid'] = $_uid;
		$where['subject'] = 'PV';
		$reid = "";
		$val = $pvm->field('value')->where($where)->find();
		$data = array();
		$data['userid'] = $_uid;
		$data['subject'] = 'PV';
		$data['platform'] = 'SMW01';
		$data['value'] = $_mun;
		if($val['value']){
			$temp = array();
			$temp['value'] = $val['value'] + $_mun;
			$reid = $pvm->where($where)->save($temp);
		}else {
			$data['mtime'] = time();
			$reid = $pvm->add($data);
		}
		if($reid){
			$data['action_userid'] = $_uid;
			$data['nowvalue'] = $val['value'];
			$data['ctime'] = time();
			$data['cip'] = get_client_ip();
			$data['bzvu'] = "$_sn";
			$data['changtype'] = 'ORDER_USE';
			$reid = $pva->add($data);
			return $reid;			
		}else{
			return $reid;
		}
	}
	
	/**
	 * 根订单ID返回订单优惠券
	 * @param array $_orderid
	 * @return array $Info
	 */
	function b2b_order_coupon($_orderid = 'all'){
		$model = M('OrderCoupon');
		$where = array();
		$where['platfrom'] = 'SMW01';
		$_orderid == 'all' ? true : $where['order_id'] = is_array($_orderid) ? array("IN",implode(',', $_orderid)) : $_orderid;
		$info = $model->where($where)->select();
		// 		echo $model->getLastSql();
		return $info;
	}
	
	/**
	 * 根订单ID返回订单商品详情
	 * @param array $_orderid
	 * @return array $Info
	 */
	function b2b_order_goods($_orderid = 'all'){
		$model = M('OrderGoods');
		$where = array();
		$where['platfrom'] = 'SMW01';
		$_orderid == 'all' ? true : $where['order_id'] = is_array($_orderid) ? array("IN",implode(',', $_orderid)) : $_orderid;
		$info = $model->where($where)->select();
		// 		echo $model->getLastSql();
		return $info;
	}
	
	/**
	 * 根订单ID返回订单财务信息
	 * @param array $_orderid
	 * @return array $Info
	 */
	function b2b_order_finance($_orderid = 'all',$_express = FALSE){
		$model = M('OrderFinance');
		$where = array();
		$where['platfrom'] = 'SMW01';
		$_orderid == 'all' ? true : $where['order_id'] = is_array($_orderid) ? array("IN",implode(',', $_orderid)) : $_orderid;
		$_express ? FALSE : $where['code'] = 'amount';
		$info = $model->where($where)->select();
		if(! $_express){
			return field2key($info,'order_id');
		}
		return $info;
	}
	 
	/**
	 * 根订单ID返回订单基本信息
	 * @param array $_orderid
	 * @return array $Info
	 */
	function b2b_order($_orderid = 'all'){
		$model = M('Order');
		$where = array();
		$where['platfrom'] = 'SMW01';
		$_orderid == 'all' ? true : $where['id'] = is_array($_orderid) ? array("IN",implode(',', $_orderid)) : $_orderid;
		$info = $model->where($where)->select();
// 		echo $model->getLastSql();
		$info = field2key($info,'id');
		return $info;
	}
	
	
	/**
	 * 获取订单的详情
	 *
	 * @param int $id        	
	 * @param string $ext
	 *        	需要调用的订单扩展 all全部 多个使用 ,
	 * @param string $notext
	 *        	需要排除的订单扩展
	 * @return array @date 2013-5-15
	 *         @time 下午6:59:45
	 */
	function order_detail($id = 0, $ext = 'all', $notext = '') {
		// 获取订单的详情
		$this->line = 'order_detail::' . __LINE__;
		// 获取订单的基本信息
		$data = $this->orderdao->find ( $id );
		if (empty ( $data )) {
			return false;
		}
		// 获取财务信息（分退款，其它）
		if (($ext == 'all' || $ext == 'finance') && $notext != 'finance') {
			$data ['finance'] = self::order_finance ( $data ['id'] );
		}
		// 获取商品信息（O2O平台关联商品扩展信息）
		if (($ext == 'all' || $ext == 'goods') && $notext != 'goods') {
			$data ['goods'] = self::order_goods ( $data ['id'] );
		}
		// 获取优惠券
		if (($ext == 'all' || $ext == 'coupon') && $notext != 'coupon') {
			$data ['coupon'] = self::order_coupon ( $data ['id'] );
		}
		// 获取扩展信息
		if (($ext == 'all' || $ext == 'ext') && $notext != 'ext') {
			$data ['ext'] = self::order_ext ( $data ['id'] );
		}
		if (($ext == 'all' || $ext == 'address') && $notext != 'address') {
			$data ['address'] = self::order_address ( $data ['id'] );
		}
		if (($ext == 'all' || $ext == 'logs') && $notext != 'logs') {
			$data ['logs'] = self::order_logs ( $data ['id'] );
		}
		return $data;
	} // end order_detail
	
	/**
	 * 获取订单的优惠券信息
	 * @date 2013-6-26
	 * @time 下午6:03:07
	 */
	function order_coupon($orderids = array()) {
		// 获取订单的优惠券信息
		if (empty ( $orderids )) {
			self::_err ( '参数缺失' );
		}
		$dao = M ( 'OrderCoupon' );
		$where = array ();
		$ids = array ();
		if (is_array ( $orderids )) {
			foreach ( $orderids as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderids;
		}
		$where ['order_id'] = array (
				'IN',
				implode ( ',', $ids ) 
		);
		$data = $dao->where ( $where )->select ();
		$temp = array ();
		if (count ( $orderids ) == 1) {
			$temp = $temp [$orderids [0]];
		} else {
			foreach ( $data as $v ) {
				$orderids [$v ['order_id']] ['coupon'] [] = $v;
			}
			$temp = $orderids;
		}
		return $temp;
	} // end order_coupon
	
	/**
	 * 获取订单的操作记录
	 * 
	 * @param array $orderids
	 *        	订单编号
	 * @param string $open
	 *        	开放的类型 全部大写
	 *        	@date 2013-7-4
	 *        	@time 上午9:42:57
	 */
	function order_logs($orderids = array(), $open = 'ALL') {
		// 获取订单的操作记录
		if (empty ( $orderids )) {
			self::_err ( '参数缺失' );
		}
		$dao = M ( 'OrderLogs' );
		$where = array ();
		$ids = array ();
		if (is_array ( $orderids )) {
			foreach ( $orderids as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderids;
		}
		$where ['order_id'] = array (
				'IN',
				implode ( ',', $ids ) 
		);
		if ($open != 'ALL') {
			$where ['open'] = array (
					'IN',
					$open 
			);
		}
		$data = $dao->where ( $where )->select ();
		$temp = array ();
		if (count ( $orderids ) == 1) {
			$temp = $temp [$orderids [0]];
		} else {
			foreach ( $data as $v ) {
				$orderids [$v ['order_id']] ['logs'] [] = $v;
			}
			$temp = $orderids;
		}
		return $temp;
	} // end order_logs
	
	/**
	 * 获取订单财务信息(SYS)
	 *
	 * @access protected
	 * @param array $orderids=array()
	 *        	订单ID数组
	 * @return array $finance 订单财务明细数组
	 *         @date 2013-5-15
	 *         @time 下午7:00:29
	 */
	function order_finance($orderids = array()) {
		// 获取订单财务信息
		$this->line = 'order_finance::' . __LINE__;
		$this->debug = $orderids;
		if (empty ( $orderids )) {
			self::_err ( '参数缺失' );
		}
		$dao = M ( 'OrderFinance' );
		$where = array ();
		$ids = array ();
		if (is_array ( $orderids )) {
			foreach ( $orderids as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderids;
		}
		$where ['order_id'] = array (
				'IN',
				implode ( ',', $ids ) 
		);
		$data = $dao->where ( $where )->order ( 'id ASC' )->select ();
		$temp = array ();
		if (! is_array ( $orderids )) {
			$temp = $data;
		} else {
			foreach ( $data as $v ) {
				$orderids [$v ['order_id']] ['finance'] [] = $v;
			}
			$temp = $orderids;
		}
		return $temp;
	} // end order_finance
	
	/**
	 * 获取订单的扩展信息 (O2O的订单需要获取扩展信息)
	 * @date 2013-5-18
	 * @time 下午6:23:40
	 */
	function order_ext($orderlist = array()) {
		// 获取订单的扩展信息
		$this->line = '_order_ext::' . __LINE__;
		$dao = M ( "OrderExt" );
		$ids = array ();
		if (is_array ( $orderlist )) {
			foreach ( $orderlist as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderlist;
		}
		$list = $dao->field ( 'element,value,name,order_id' )->where ( array (
				'order_id' => array (
						'IN',
						implode ( ',', $ids ) 
				) 
		) )->select ();
		$temp = array ();
		foreach ( $list as $v ) {
			if (is_array ( $orderlist )) {
				$orderlist [$v ['order_id']] ['ext'] [$v ['element']] = $v;
			} else {
				$temp [$v ['element']] = $v;
			}
		}
		if (! is_array ( $orderlist )) {
			$orderlist = $temp;
		}
		return $orderlist;
	} // end _order_ext
	
	/**
	 * 获取订单商品及商品扩展信息
	 * 
	 * @param array $orderid
	 *        	订单ID
	 *        	@date 2013-5-18
	 *        	@time 下午6:24:21
	 */
	function order_goods($orderid = array()) {
		// 获取订单商品及商品扩展信息
		$this->line = 'order_goods::' . __LINE__;
		$dao = M ( 'OrderGoods' );
		$ids = array ();
		if (is_array ( $orderid )) {
			foreach ( $orderid as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderid;
		}
		$where = array ();
		$where ['order_id'] = array (
				'IN',
				implode ( ',', $ids ) 
		);
		$res = array ();
		$data = $dao->where ( $where )->select ();
		if (is_array ( $orderid )) {
			foreach ( $data as $v ) {
				$res [$v ['order_id']] ['goods'] [$v ['id']] = $v;
			}
		} else {
			$res = $data;
		}
		return $res;
	} // end order_goods
	
	/**
	 * O2O的订单商品
	 * 
	 * @param array $orderid
	 *        	订单ID
	 *        	@date 2013-6-18
	 *        	@time 下午7:46:37
	 */
	function o2o_order_goods($orderid = array()) {
		// O2O的订单商品
		$dao = D ( 'GoodsV' );
		$ids = array ();
		if (is_array ( $orderid )) {
			foreach ( $orderid as $v ) {
				$ids [] = $v ['id'];
			}
		} else {
			$ids [] = $orderid;
		}
		$where = array ();
		$where ['order_id'] = array (
				'IN',
				implode ( ',', $ids ) 
		);
		$res = array ();
		$data = $dao->where ( $where )->select ();
		if (is_array ( $orderid )) {
			foreach ( $data as $v ) {
				$res [$v ['order_id']] ['goods'] [$v ['id']] = $v;
			}
		} else {
			$res = $data;
		}
		return $res;
	} // end order_goods
	
	/**
	 * 获取订单的配送信息
	 * @date 2013-5-18
	 * @time 下午6:25:00
	 */
	function order_address($orderid = array(),$address_id=0) {
		// 获取订单的配送信息
		if($address_id!=0){
			$dao = M ('UserAddress');
			$where = array ();
			$where['id']=$address_id;
			$field='consignee,province,city,district,address,mobile,tel,email';
			$res = array ();
			$data = $dao->field($field)->where ( $where )->select ();
			$res = $data ['0'];
		}else{
			$dao = M ('OrderAddress');
			$ids = array ();
			if (is_array ( $orderid )) {
				foreach ( $orderid as $v ) {
					$ids [] = $v ['id'];
				}
			} else {
				$ids [] = $orderid;
			}
			$where = array ();
			$where ['order_id'] = array (
					'IN',
					implode ( ',', $ids )
			);
			$res = array ();
			$data = $dao->where ( $where )->select ();
			if (is_array ( $orderid )&&$address_id==0) {
				foreach ( $orderid as $v ) {
					$orderid [$v ['order_id']] ['address'] [$v ['id']] = $v;
				}
			} else {
				$res = $data ['0'];
			}
		}
		return $res;
	} // end _order_address
	
	/**
	 * 获取O2O平台订单详情（O2O平台）
	 * @date 2013-5-15
	 * @time 下午5:56:28
	 */
	function o2o_order_detail() {
		// 获取O2O平台订单详情（O2O平台）
		$this->line = 'o2o_order_detail' . __LINE__;
		;
	} // end o2o_order_detail
	
	/**
	 * 获取商户的订单（O2O平台）
	 * @date 2013-5-15
	 * @time 下午5:59:04
	 *
	 * @param array $sid 自提点ID，可以是一维数组
	 * @param array $cid 云购店的ID，可以是一维数组
	 * @return array()
	 */
	function o2o_order_biz($sid = array(),$type='',$limit = '0,20', $order = 'id DESC') {
		// 获取商户的订单（O2O平台）
		$this->line = 'o2o_order_biz::' . __LINE__;
		if(is_array($sid)){
			$sid=implode(',', $sid);
		}
		$ext = M ( 'OrderExt' );
		$where=array (
			'element' =>$type,
			'value' => array('IN',$sid)
		);
		$ids = $ext->field ( 'order_id' )->where ($where)->select ();
		if (empty ( $ids )) {
			return self::_err ( '暂无相关数据' );
		}
		$ids = arr_to_explode ( $ids, 'order_id', ',' );
		$dao = M ( 'Order' );
		$where = array ();
		$where ['platform'] = '91YUNGOU';
		$where ['id'] = array (
				'IN',
				$ids
		);
		if (strtolower ( $limit ) == 'all') {
			return $dao->where ( $where )->count ();
		}
		$data = $dao->where ( $where )->order ( $order )->limit ( $limit )->select ();
		$data = field2key ( $data, 'id' );
		$data = self::order_ext ( $data );
		if (empty ( $data )) {
			return self::_err ( '暂无相关数据' );
		} else {
			return $data;
		}
	} // end o2o_order_biz
	
	/**
	 * 获取单个用户的所有订单
	 * @date 2013-5-15
	 * @time 下午6:12:21
	 */
	function o2o_order_user($userid = 0, $limit = '0,20', $order = 'id DESC') {
		// 获取单个用户的所有订单
		$this->line = 'o2o_order_user::' . __LINE__;
		$ext = M ( 'OrderExt' );
		$ids = $ext->field ( 'order_id' )->where ( array (
				'element' => 'userid',
				'value' => $userid 
		) )->select ();
		// dump($ext->getLastSql());
		if (empty ( $ids )) {
			return self::_err ( '暂无相关数据' );
		}
		$ids = arr_to_explode ( $ids, 'order_id', ',' );
		$dao = M ( 'Order' );
		$where = array ();
		$where ['platform'] = '91YUNGOU';
		$where ['id'] = array (
				'IN',
				$ids 
		);
		if (strtolower ( $limit ) == 'all') {
			return $dao->where ( $where )->count ();
		}
		$data = $dao->where ( $where )->order ( $order )->limit ( $limit )->select ();
		$data = field2key ( $data, 'id' );
		$data = self::order_ext ( $data );
		if (empty ( $data )) {
			return self::_err ( '暂无相关数据' );
		} else {
			return $data;
		}
	} // end o2o_order_user_list
	
	/**
	 * b2b会员订单详情
	 * */
	function b2b_order_user_detail($id =array(),$field='id'){
		// 用户订单详情
		$this->line = 'b2b_order_user_detail::' . __LINE__;
		$dao = M ( 'Order' );
		$where = array ();
		if(!is_array($id)){
			$where [$field] = $id;
		}else{
			$where [$field] =array('IN',implode(',', $id));
		}
		$data=$dao->where ( $where )->select();
		if(!is_array($id)){
			$data=$data['0'];
		}
		return $data;
	} // end b2b_order_user_detail
	/**
	 * 用户订单详情
	 * @date 2013-6-18
	 * @time 下午3:20:21
	 */
	function o2o_order_user_detail($id =array(),$field='id') {
		// 用户订单详情
		$this->line = 'o2o_order_user_detail::' . __LINE__;
		$dao = M ( 'Order' );
		$where = array ();
		if(!is_array($id)){
			$where [$field] = $id;
		}else{
			$where [$field] =array('IN',implode(',', $id));
		}
		$data=$dao->where ( $where )->select();
		if(!is_array($id)){
			$data=$data['0'];
		}
		return $data;
	} // end o2o_order_user_detail
	
	/**
	 * 根据订单ID返回优惠信息
	 * @param int|string $_orid
	 * @return array $info
	 */
	function couponinfo($_orid,$_type = FALSE){
		$model = M('OrderCoupon');
		$where = array();
		$where['order_id'] = is_array($_orid) ? array("IN",implode(",", $_orid)) : $_orid;
		$_type ? $where['type'] = $_type : FALSE;
		$temp = $model->where($where)->select();
		$info = array();
		$info = field2key($temp, 'order_id');
// 		foreach ($temp as $k => $v){
// 			$info[$v['order_id']][] = $v;
// 		}
		return $info;
	}
	
	/**
	 * 批量导出订单的出库单
	 * @date 2013-5-18
	 * @time 下午6:29:11
	 */
	function export_bill() {
		// 批量导出订单的出库单
		$this->line = 'export_bill::' . __LINE__;
		;
	} // end export_bill
	
	
	/**
	 * 商户订单统计
	 * @date 2013-9-6
	 * @time 上午11：29
	 */
	function o2o_order_count($sid = array(),$type='') {
		$ext = M ( 'OrderExt' );
		$where=array (
				'element' =>$type,
				'value' => array('IN',$sid)
		);
		//获取商户订单ids
		$ids = $ext->field ( 'order_id' )->where ($where)->select ();
		if (empty ( $ids )) {
			return array();
		}
		$ids = arr_to_explode ( $ids, 'order_id', ',' );
	
		//创建搜索条件
		$search = array(
				'order_dfh' => array('shipping_status'=>0), //待发货订单
				'order_dsl' => array('userid'=>0), //待受理订单
				'order_dqr' => array('status'=>0), //待确认订单
				'order_dzf' => array('pay_status'=>0), //待支付订单
				'order_ycj' => array('status'=>10) //已成交订单
		);
	
		$res = array();
		foreach ($search as  $key=>$arr){
			$where = array();
			$where ['platform'] = '91YUNGOU';
			$where ['id'] = array ('IN',$ids);
			foreach ($arr as $vo_key => $value ){
				$where[$vo_key] = $value;
				$res[$key] = $this->orderdao->where($where)->count();
// 				if($count){
// 					$res[$key] = $count;
// 				}else{
// 					$res[$key] = 23;
// 				}
				
			}
		}
		return $res;
	}
	
	/**
	 * 输出错误信息
	 * @date 2013-5-6
	 * @time 下午5:19:24
	 */
	function _err($arr = array(), $str = "暂无相关信息") {
		// 请求接口类型异常
		if ($this->isdebug == 1) {
			echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
		}
		if (is_array ( $arr ) && ! empty ( $arr )) {
			$res = array (
					"status" => 0,
					"msg" => $str,
					'data' => $arr,
					'line' => $this->line 
			);
		} else {
			$res = array (
					"status" => 0,
					"msg" => $str,
					'data' => $this->debug,
					'line' => $this->line 
			);
		}
		$res = json_encode ( $res );
		if ($this->err91yungou == 1) {
			self::err91yungou ( $res );
		}
		return $res;
		if ($this->isdebug == 1) {
			echo '</textarea>';
		}
		die ();
	} // end _err
	
	/**
	 * 请求成功返回
	 * @date 2011-11-15
	 * @time 上午08:10:19
	 */
	private function _suc($arr = array(), $str = "操作成功") {
		// 请求接口类型异常
		$res = array (
				"status" => 1,
				"msg" => $str,
				'data' => $this->debug 
		);
		if (! empty ( $arr )) {
			$res = array_merge ( $res, $arr );
		}
		if ($this->isdebug == 1) {
			echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
		}   
		echo myjson ( $res );
		if ($this->isdebug == 1) {
			echo '</textarea>';
		}
		die ();
	} // end _suc
	
	/**
	 * 91云够的错误输出
	 * @date 2013-6-8
	 * @time 下午10:26:43
	 */
	function err91yungou($str = '') {
		// 91云够的错误输出
		exit ( $str );
	} // end err91yungou
	
	/**
	 * 返回订单的优惠信息
	 * @param int | array $_orderid
	 * @return array $ifno
	 */
	function ordercoupon($_orderid){
		$model = M("OrderCoupon");
		$where = array();
		$where['order_id'] = is_array($_orderid) ? array('IN',implode(',', $_orderid)) : $_orderid;
		$info = $model->where($where)->select();
		return $info;
	}
}//end OrderSelect